########
# What does this do?
#######
rm(list=ls())

# load libraries
packs = c('tidyverse', 'igraph', 'hrbrthemes', 'wesanderson', 'Cairo')
source("replication/r/LoadPkg.R")
source('replication/r/reiter_stam_2003/helperEx.R')
loadPkg(packs)

# read data
load("replication/data/before.RData") 
load("replication/data/after.RData") 


# descriptive stats
before$type = 'Before ISIL'
after$type = 'After ISIL'

both = rbind(before, after)

# Figure A.2:
ggplot(both, aes(x = pos, fill = type)) + 
  geom_histogram(position = position_dodge()) +
  theme_ipsum(grid = 'Y') + 
  labs(x = '', y = 'Count of positive events', fill = c('After', 'Before')) + 
  scale_fill_manual(values = wesanderson::wes_palette("Darjeeling1", 
                                                      n = 2, type = 'discrete')) + 
  theme(legend.title = element_blank(), 
        legend.position = 'top')
ggsave('replication/paper/figures/count-pos-events.pdf', device = cairo_pdf)

# turn into adjacency matrices
beforeAdjComb = 
  data.frame(ego = before$SourceCountry, 
             alter = before$TargetCountry,
             valence = before$simon)

beforeAdjComb = graph.data.frame(beforeAdjComb, directed=FALSE)
beforeAdjComb = get.adjacency(beforeAdjComb, attr="valence")

afterAdjComb = 
  data.frame(ego = after$SourceCountry, 
             alter = after$TargetCountry, 
             valence = after$simon)

afterAdjComb = graph.data.frame(afterAdjComb, directed=FALSE)
afterAdjComb = get.adjacency(afterAdjComb, attr="valence")


# eigenvector decomposition
facs_before = eigen(beforeAdjComb)
facs_after = eigen(afterAdjComb)


bef_eigen = data.frame(country = rownames(beforeAdjComb), 
                       xdim = facs_before$vectors[,1], 
                       ydim = facs_before$vectors[,2], 
                       type = 'Before')

aft_eigen = data.frame(country = rownames(afterAdjComb), 
                       xdim = facs_after$vectors[,1], 
                       ydim = facs_after$vectors[,2], 
                       type = 'After')


pDat = rbind(bef_eigen, aft_eigen)

# plot Figure A.3:
ggplot(pDat, aes(x = xdim, y = ydim, label = country)) + 
  geom_point() + 
  ggrepel::geom_label_repel() + 
  facet_grid(~type) + 
  theme_light() + 
  labs(x = '', y = '') + 
  theme(panel.border = element_blank(), 
        axis.text.x = element_blank(), 
        axis.text.y = element_blank(), 
        panel.grid.minor = element_blank(), 
        axis.ticks = element_blank(), 
        strip.background = element_rect(fill = 'black'))
ggsave('replication/paper/figures/eigen-vector-decomp.pdf', device = cairo_pdf)
